//index.js
//获取应用实例
import S_request from '../../utils/requestService.js';
import CONFIG from '../../config.js';
const app = getApp()
let gameId = 0 //详情页id
let redPackId = 0; //语音红包编号id
let isNetWork = true; //默认是true，又网络
let hongbaoId = 0; //通过二维码扫码进入语音红包
let formId = 0; //表单Id
let dbId = 0; //夺宝详情页分享跳转的
let gameTitle = '' //渠道标题
Page({
  data: {
    gameList: [],
    modalObj: {},
    isShow: false, // 弹框
    isShowTask: false,
    isShowNetWork: false, //没有网络显示
    modalDealIdx: 0, // 弹框的操作对象Idx
    isShowTabbar: false, //tabbar是否显示
    scene: "", //获取场景值
    shareType: 0, //分享类型,
    userId: '', //记录分享的人
    quickAddDisp: "none", //是否显示快捷添加
    bannerList: {}, //轮播图
    noticeList: {}, //公告
    indicatorDots: false, //是否显示面板指示点
    autoplay: true, //是否自动切换
    interval: 3000, //自动切换时间间隔,3s
    duration: 1000, //  滑动动画时长1s
    circular: true, //是否采用衔接滑动
    preMargin: 10,
    nextMargin: 10,
    swiperCurrent: 0, //当前的位置
    isShowGold: false, //玩游戏领金币弹框提示
    isShowGY: false, //是否显示公益界面
    isShowGYDia: false, //公益弹窗
    isShowGYAth:false, //公益是否授权
  },
  onShareAppMessage: function(res) {
    wx.showShareMenu({
      withShareTicket: false,
      success: function() {}
    });
    let obj = { 'pagepath': CONFIG.SHARE.path}
    S_request.index.recordShare("-1", obj);
    console.log("sharePath====" + CONFIG.SHARE.path)
    let title = '', imageUrl = '';
    if (gameTitle == '即有爱•公益中心') {
      let nickname = '亲，'
      if (app.globalData.userInfo != null) {
        nickname = app.globalData.userInfo.nickName;
      }
      title = nickname + "邀请你来为即有爱·公益事业助力。"
      imageUrl = CONFIG.SHARE.gyImageUrl
    } else {
      title = CONFIG.SHARE.title
      imageUrl = CONFIG.SHARE.imageUrl
    }
    return {
      title: title,
      path: CONFIG.SHARE.path,
      imageUrl: imageUrl
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getSetting();
    let self = this;
    let share = options.share;
    //share: 1普通分享  2抽奖分享 3商城分享 4详情页分享 5语音红包分享 6夺宝分享
    if (share >= 1) {
      this.setData({
        shareType: share
      })
      if (share == 4) { //详情页分享
        gameId = options.gameId
      }
      if (share == 5) { //红包编号id
        redPackId = options.redPackId;
      }
      if (share == 6) { //夺宝界面
        let id = options.dbId;
        if (id && id != 'undefined' && id != '') {
          dbId = id;
        }
      }
      console.log("游戏界面转发==" + share)
    }
    // ======通过二维码进入语音红包界面
    let hbId = decodeURIComponent(options.hongbaoId)
    if (hbId && hbId != 'undefined' && hbId != '') {
      hongbaoId = hbId;
    }
    // ======通过二维码进入语音红包界面
    //options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    //decodeURIComponent(options.scene) ,在app.js lanuch中处理
    let scene = app.globalData.enterScene;
    if (scene && scene != 'undefined' && scene != '') {
      this.setData({
        scene: scene
      })
    }
    console.log("scene===" + this.data.scene)
    let userId = options.fu;
    if (userId && userId != 'undefined' && userId != '') {
      this.setData({
        userId: userId
      })
    }
    console.log("userId===" + this.data.userId)
    this.loadPageData();
    //是否显示'玩游戏领金币'提示
    // this.showGold();
  },
  enterScenePro: function() {
    let scene = this.data.scene;
    if (scene && scene != 'undefined' && scene != '') {
      S_request.index.enterScenePro(scene, (result) => {
        if (result.programid != 0 && result.programid != '') {
          wx.navigateTo({
            url: result.programid,
          })
        }
      })
    }

  },
  isShowQuickAdd: function() {
    let token = wx.getStorageSync("token");
    if (token == '') return;
    S_request.index.quickAddReward(1, (result) => {
      console.log("游戏界面 快速添加" + JSON.stringify(result))
      if (result.code == 404) {
        this.setData({
          quickAddDisp: "block"
        })
      } else if (result.code == 503) {
        this.setData({
          quickAddDisp: "none"
        })
      }
    })
  },
  getBannerList: function() {
    S_request.index.bannerList((result) => {
      this.setData({
        bannerList: result.lists
      })
    })
  },
  getNotices: function() {
    S_request.index.getNotices((result) => {
      this.setData({
        noticeList: result.lists
      })
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getGameList(this.data.scene, this.data.userId, this.data.shareType);
    this.getNetworkStatus();
    this.showTaskDialog();
    this.isShowQuickAdd();
  },
  showTaskDialog: function() {
    if (gameTitle == '即有爱•公益中心') return;
    if (app.globalData.taskNum == 0) {
      this.setData({
        modalDealIdx: 0,
        isShowTask: false
      });
    } else if (this.data.isShowTask != true) {
      let animation1 = wx.createAnimation({
        transformOrigin: "50% 50%",
        duration: 800,
        timingFunction: "ease",
      });
      animation1.scale(0.4).step();
      this.data.modalObj.animation = animation1.export();
      this.data.modalObj.taskNum = app.globalData.taskNum;
      this.setData({
        modalDealIdx: 1,
        isShowTask: true,
        modalObj: this.data.modalObj
      });

      setTimeout(function() {
        animation1.scale(1).step()
        this.data.modalObj.animation = animation1.export();
        this.setData({
          modalObj: this.data.modalObj
        })
      }.bind(this), 500)
    } else {
      this.data.modalObj.taskNum = app.globalData.taskNum;
      this.setData({
        modalObj: this.data.modalObj
      });
    }
  },
  dynaUpdateTitle: function() {
    //实现渠道定制，动态修改标题名字
    gameTitle = wx.getStorageSync("gameTitle");
    if (gameTitle == "") {
      gameTitle = '多好玩乐园'
    }
    wx.setNavigationBarTitle({
      title: gameTitle
    });
    if (gameTitle == '即有爱•公益中心') {
      wx.setTabBarItem({
        index: 0,
        text: '公益游戏'
      });
      this.setData({
        isShowGY: true,
      })
      this.showGYDia()
    } else {
      this.setData({
        isShowGY: false
      })
    }
  },
  showGYDia: function() {
    let time = wx.getStorageSync('gy_time');
    let date = new Date();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let timeNow = month + "-" + day;
    if (time == '') {
      this.data.modalObj.isShow = true
      this.setData({
        isShowGYDia: true,
        modalObj: this.data.modalObj
      })
      wx.setStorageSync('gy_time', timeNow)
    } else {
      // this.setData({
      //   isShowGYDia: false
      // })
    }

  },
  confirmAc: function() {
    this.setData({
      isShowGYDia: false
    })
  },
  getGameList: function(scene, userId, share) {
    let token = wx.getStorageSync("token");
    if (token == '') return;
    let self = this;
    S_request.index.getNewGameList(scene, userId, share, (data) => {
      //动态设置首页名字
      // console.log("ahsahsha==="+JSON.stringify(data))
      wx.setStorageSync("gameTitle", data.title);
      self.dynaUpdateTitle();
      let lists = data.lists;
      app.globalData.gameLists = lists;
      for (let i = 0; i < lists.length; i++) {
        let item = lists[i];
        for (let i = 0; i < item.list.length; i++) {
          let tempItem = item.list[i];
          if (tempItem.zhulijine == 0) {
            tempItem.zhuliTxt = tempItem.zhuliwenzi;
            tempItem.zhuli = 0;
          } else {
            if (tempItem.hasOwnProperty('zhuli')) {
              tempItem.zhuliTxt = "已" + tempItem.zhuliwenzi;
              tempItem.zhuli = tempItem.zhuli;
            } else {
              tempItem.zhuliTxt = tempItem.zhuliwenzi;
              tempItem.zhuli = 0;
            }
          }
        }
        let viewHeight = 0,
          viewDisplay = 'none';
        if (item.list.length <= 4) {
          viewHeight = 358
          item.list1 = item.list;
          viewDisplay = 'none'
        } else {
          viewHeight = 358 + (item.list.length - 4) / 2 * 270;
          viewDisplay = 'block';
          item.list1 = [], item.list2 = [];
          for (let j = 0; j < item.list.length; j++) {
            let temp = item.list[j];
            if (j < 4) {
              item.list1.push(temp);
            } else {
              item.list2.push(temp);
            }
          }
        }
        item.viewHeight = viewHeight;
        item.viewDisplay = viewDisplay;
      }
      // console.log("aaaaa===" + JSON.stringify(data));
      self.setData({
        gameList: lists
      });
    }, this)
  },
  getGoldNum: function(shareType) {
    S_request.index.getUserInfo((data) => {
      // console.log("fenxiang index===="+JSON.stringify(data))
      app.globalData.goldnum = data.user.goldcoin;
      if (shareType == 2) {
        wx.navigateTo({
          url: '../choujiang/choujiang'
        });
      } else if (shareType == 3) {
        wx.navigateTo({
          url: '../shop/shop'
        });
      }
    })
  },
  getTaskList: function() {
    let self = this;
    if (gameTitle == '即有爱•公益中心') return;
    S_request.mine.getTaskList((data) => {
      wx.setStorageSync("userId", data.user.id);
      let tasks = data.tasks;
      let taskNum = 0;
      for (let i = 0; i < tasks.length; i++) {
        let item = tasks[i];
        if (item.status == 2) { //完成还未领取奖励
          taskNum++;
        }
      }
      console.log("taskNum====" + taskNum);
      app.globalData.taskNum = taskNum;
      self.showTaskDialog();
    }, this)
  },
  playGame: function(e) {
    let id = e.currentTarget.dataset.id;
    console.log("id====" + id + ",formId ===" + formId);
    let param = 'formId=' + formId +"&eventid=10"
    S_request.index.tongJiNum(id, param, (result) => {
      console.log("data====" + result);
    })
    let path = e.currentTarget.dataset.path;
    if (path != undefined && path != '') {
      wx.navigateTo({
        url: path,
      })
    } else {
      if (gameTitle != '即有爱•公益中心') return;
      let zhulijine = e.currentTarget.dataset.jine;
      let zhuli = e.currentTarget.dataset.zhuli;
      let url = e.currentTarget.dataset.url;
      // if (zhulijine == 0 || zhuli == 1)return;
      setTimeout(function() {
        this.data.modalObj.isShow = false
        this.data.modalObj.id = id
        this.data.modalObj.url = url
        this.setData({
          isShowGYDia: true,
          modalObj: this.data.modalObj
        })
        this.getGameList(this.data.scene, this.data.userId, this.data.shareType);
      }.bind(this), 1000)
    }
  },
  switchTab: function(e) {
    let url = e.currentTarget.dataset.url;
    wx.switchTab({ //跳转到 tabBar 页面
      url: url
    })
  },
  openWB: function(e) {
    let id = e.currentTarget.dataset.id;
    let path = encodeURIComponent(e.currentTarget.dataset.url);
    wx.navigateTo({
      url: '../voiceRedPacket/webv/webv?url=' + path,
    })
    console.log("path====" + path)
    let param = 'formId=0' +"&eventid=8"
    S_request.index.tongJiNum(id, param, (result) => {
      console.log("data====" + result);
    })

  },
  //index暂时不适用getSetting， 在mine里面使用
  getSetting: function() {
    // 获取用户信息
    wx.getSetting({
      success: res => {
        var authSetting = res.authSetting;
        if (authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          app.globalData.isAuthorize = true;
          // this.showTabbar();
          // this.getUserInfo();
        } else if (authSetting['scope.userInfo'] == false) {
          // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
          app.globalData.isAuthorize = false;
          // this.showModal();
          // this.hiddenTabbar();
        } else {
          // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
          app.globalData.isAuthorize = false;
          // this.showModal();
          // this.hiddenTabbar();
        }
        this.isShowGYAth();
      }
    })
  },
  isShowGYAth: function () {
    console.log("isAuthorize===" + app.globalData.isAuthorize)
    if (app.globalData.isAuthorize) {
      this.getUserInfo();
      this.setData({
        isShowGYAth: false
      });
    } else {
      this.setData({
        isShowGYAth: true
      });
    }
  },
  getUserInfo: function () {
    let self = this;
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        app.globalData.userInfo = res.userInfo;
        this.setData({
          userinfo: app.globalData.userInfo,
        });
        S_request.index.updateUserInfo(res.userInfo, (result) => {
          app.globalData.isAuthorize = true;
          self.setData({
            isShowGYAth: false
          });
        });
      }
    })
  },
  onGotUserInfo: function (e) {
    let self = this;
    console.log(e.detail.errMsg)
    console.log(e.detail.userInfo)
    console.log(e.detail.rawData)
    if (!e.detail.userInfo) return;
    app.globalData.userInfo = e.detail.userInfo;
    let userInfo = e.detail.userInfo;
    S_request.index.updateUserInfo(userInfo, (result) => {
      // console.log("更新与用户信息成功====" + JSON.stringify(result));
      app.globalData.isAuthorize = true;
      self.setData({
        isShowGYAth: false
      });
    })
  },

  showModal: function() {
    this.data.modalObj.titS = '好玩的游戏，这里都有！'
    // this.data.modalObj.btnTit = '点击进入游戏世界'
    this.data.modalObj.leftBtnStyle = "display:none; background-color: #dc0000;border: 1px solid #c50101 !important";
    this.data.modalObj.confirm = "inline"
    this.data.modalObj.imageSrc = "../image/game_icon.png"
    this.data.modalObj.imageStyle = "display:block;margin-top:-50px;height: 109px;width: 106px";
    this.data.modalObj.titleStyle = "font-size:34rpx; color:#666";
    this.setData({
      modalDealIdx: 1,
      isShow: true,
      isShowTabbar: false,
      modalObj: this.data.modalObj
    })
  },
  modalLeftAc: function(e) {
    this.setData({
      modalDealIdx: 0,
      isShow: false
    })
  },
  modalRightAc: function(e) {
    // console.log("获取用户信息===" + app.globalData.userInfo)
    this.showTabbar();
    this.setData({
      modalDealIdx: 0,
      isShow: false
    })
  },
  showTabbar: function() {
    wx.showTabBar({
      aniamtion: true,
      success: res => {
        console.log("显示tabbar成功===" + res)
      },
      fail: res => {
        console.log("显示tabbar失败===" + res)
      }
    })
  },
  hiddenTabbar: function() {
    wx.hideTabBar({
      aniamtion: true,
      success: res => {
        console.log("隐藏tabbar成功===" + res)
      },
      fail: res => {
        console.log("隐藏tabbar失败===" + res)
      }
    })
  },
  getUserInfo: function() {
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        app.globalData.userInfo = res.userInfo
        console.log(app.globalData.userInfo);
        S_request.index.updateUserInfo(res.userInfo, (result) => {
          console.log("更新与用户信息成功====" + JSON.stringify(result));
          app.globalData.goldnum = result.goldcoin;
        })

        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (this.userInfoReadyCallback) {
          this.userInfoReadyCallback(res)
        }
      }
    })
  },
  openDetail: function(e) {
    let id = e.currentTarget.dataset.id;
    console.log(id);
    wx.navigateTo({
      url: '../detail/detail?gameId=' + id,
    })
  },

  clickMenu: function(e) {
    let id = e.currentTarget.dataset.id;
    console.log(e.currentTarget.dataset.id);
    for (var i = 0; i < this.data.menuList.length; i++) {
      this.data.menuList[i]["color"] = '#666666';
      this.data.menuList[i]["src"] = this.data.menuList[i]["normal"];
    }
    this.data.menuList[id - 1]["color"] = '#12baad';
    this.data.menuList[id - 1]["src"] = this.data.menuList[id - 1]["select"];
    this.data.swiperCurrent = id - 1;
    let list;
    if (id == 1) {
      list = this.data.gameList;
    } else if (id == 2) {
      list = this.data.lifeList;
    } else {
      list = this.data.toolList;
    }
    this.setData({
      menuList: this.data.menuList,
      swiperCurrent: this.data.swiperCurrent,
      scrollList: list
    })
  },
  changeCurrent: function(e) {
    console.log(e.detail);
    let current = e.detail.current;
    for (var i = 0; i < this.data.menuList.length; i++) {
      this.data.menuList[i]["color"] = '#666666';
      this.data.menuList[i]["src"] = this.data.menuList[i]["normal"];
    }
    this.data.menuList[current]["color"] = '#12baad';
    this.data.menuList[current]["src"] = this.data.menuList[current]["select"];

    let list;
    if (current == 0) {
      list = this.data.gameList;
    } else if (current == 1) {
      list = this.data.lifeList;
    } else {
      list = this.data.toolList;
    }
    this.setData({
      menuList: this.data.menuList,
      scrollList: list
    })
  },
  getNetworkStatus: function() {
    let self = this;
    //无网络时做提示no net
    wx.onNetworkStatusChange(function(res) {
      if (res.networkType == "none") {
        isNetWork = false;
        self.setData({
          isShowNetWork: true
        })
      } else {
        self.setData({
          isShowNetWork: false
        })
        if (!isNetWork) {
          isNetWork = true;
          self.loadPageData();
        }

      }

    })
  },
  againLoadAc: function() {
    let self = this;
    wx.showLoading({
      title: '',
    })

    setTimeout(function() {
      wx.hideLoading()
      self.getNetworkStatus();
    }, 1000)
  },
  loadPageData: function() {
    let self = this;
    app.checkSession(function(isShiXiao) {
      // console.log('isShiXiao==' + isShiXiao)
      app.getUserToken(isShiXiao, function(err) {
        if (!err) {
          self.dynaUpdateTitle();
          let share = self.data.shareType;
          if (share == 2 || share == 3) { //抽奖分享
            self.getGoldNum(share);
          } else if (share == 4) {
            wx.navigateTo({
              url: '../detail/detail?gameId=' + gameId,
            })
          } else if (share == 5) {
            wx.navigateTo({
              url: '../voiceRedPacket/index/index?redPackId=' + redPackId,
            })
          } else if (share == 6) {
            if (dbId == 0) {
              wx.navigateTo({
                url: '../duobao/index/index',
              })
            } else {
              wx.navigateTo({
                url: '../duobao/detail/detail?id=' + dbId,
              })
            }
          } else if (share == 101) {
            wx.navigateTo({
              url: '../voiceRedPacket/index/index?redPackId=' + hongbaoId,
            })
          }
          self.getGameList(self.data.scene, self.data.userId, share);
          self.getTaskList();
          self.isShowQuickAdd();
          self.getBannerList();
          self.getNotices();
          self.enterScenePro();
        }
      })
    })
  },
  quickAdd: function() {
    wx.navigateTo({
      url: '../quickAdd/quickAdd',
    })
  },
  shareAni: function() {
    let animation1 = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 200,
      timingFunction: "ease"
    });
    animation1.rotation(45).step();
    this.setData({
      animation1: animation1.export()
    });
  },
  showGold: function() {
    let time = wx.getStorageSync('time');
    let date = new Date();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let timeNow = month + "-" + day;
    if (time == '' || time != timeNow) {
      this.setData({
        isShowGold: true
      })
      wx.setStorageSync('time', timeNow)
    } else {
      this.setData({
        isShowGold: false
      })
    }

  },
  closeAc: function() {
    this.setData({
      isShowGold: false
    })
  },
  formSubmit: function(e) {
    formId = e.detail.formId;
    console.log('form发生了submit事件，携带数据为：', e.detail.value + ", " + e.detail.formId)
    // if (e.detail.formId != 'the formId is a mock one') {
    //   this.setData({
    //     formIdString: e.detail.formId + "," + this.data.formIdString
    //   })
    // }
    // console.log(this.data.formIdString)
  },




  //公益 渠道

})